<?php

// deny request if user group < 1
if (!isset($_SESSION['a_group']) || $_SESSION['a_group'] != 1) {
    Js::alert(fl('err_access'));
    exit;
}

$perPage        = Config::get('num_per_page');
$dbConditions   = array();

// processing input data
$keywords   = Form::input('kw', '', '', 'GET');
$sortField  = Form::input('sort', 'a', 'username', 'GET');
$sortOrder  = Form::input('order', '0', '0', 'GET');
$pageNum    = isset($_GET['p']) ? intval($_GET['p']) : 1;

if ($pageNum < 1) {
    $pageNum = 1;
}

// preparing SQL statement
if (!empty($keywords)) {
    $sqlKeywords = mysql_escape_string($keywords);
    $dbConditions[] = "us_fullname LIKE '%$sqlKeywords%' OR us_username LIKE '%$sqlKeywords%'";
}

$sort = null;
if ('' == Form::err('sort') && '' == Form::err('order')) {
    $sort = array(getSortField($sortField) => '0' == $sortOrder ? 'ASC' : 'DESC');
}

$totalRows = Db::getOneField('COUNT(*)', 'useradmin', $dbConditions);

$rows = db()->getAll("SELECT useradminid, us_fullname, us_username, us_e2group, us_email, us_phone, us_address
    FROM useradmin " . db()->buildWhere($dbConditions) . " " . db()->buildSort($sort) . " LIMIT " .
    Tpl::offset($perPage) . ", " . $perPage);

$startingCounter = ($pageNum - 1)*$perPage;
$keywords = htmlspecialchars($keywords);

$urlParams = $_GET;
$urlParams['p'] = '';
$paging = Tpl::page($totalRows, $perPage, 'admin?' . http_build_query($urlParams), 3, 10);

if (1 == $_SESSION['a_group']) {
    $linkAddNew = '<div><a href="useradmin/mode/edit">' . fl('add_new') . '</a></div>
        <br />';
} else {
    $linkAddNew = '';
}

function getSortField($field)
{
    $dbSortFields = array(
        'username'  => 'us_username',
        'group'     => 'us_e2group',
        'fullname'  => 'us_fullname',
        'email'     => 'us_email',
        'address'   => 'us_address',
        'phone'     => 'us_phone'
    );

    return isset($dbSortFields[$field]) ? $dbSortFields[$field] : 'us_username';
}

function getSortUrl($field)
{
    $urlParams = $_GET;

    $urlParams['sort'] = $field;

    if (!isset($_GET['sort']) || empty($_GET['sort'])) {
        $urlParams['order'] = '0';
    } else {
        $urlParams['order'] = '0' === $_GET['order'] ? '1' : '0';
    }

    return 'useradmin?' . http_build_query($urlParams);
}